<script>
//设置配置
        var ops = {
            animation: 100,
            //拖动结束
            onEnd: function (evt) {
				var tar = evt.target || evt.srcElement;
				var myElement = tar.getElementsByTagName('span');
				var arr=[];
				for(var i = 0; i < myElement.length; i++) {
				     var myGrandChildren = myElement[i].getAttribute('data-id');
					 arr.push(myGrandChildren);
				}
				arr=arr.toString();
				$.get('/index.php/Seller/Goods/item_sort/ids/'+arr,function(res){
					console.log(res);
				});
            }
        };
</script>
<table class="table table-bordered" id="goods_spec_table1">                                
    <tr>
        <td colspan="2"><b>商品规格:</b> &nbsp;&nbsp;<span style="color: red;">( 点击规格可取消/选中 )</span></td>
    </tr>
    <foreach name="specList" item="vo" key="k" >
		<?php
		echo "<script> var sortable = Sortable.create(document.getElementById('example".$k."'), ops);</script>";
		?>
    <tr>
        <td>{$vo[name]}:</td> 
        <td id="example{$k}">
            <foreach name="vo[spec_item]" item="vo2" key="k2" >
				<span data-id="{$k2}">
				<img width="35" height="35" src="/Public/images/update-button.jpg" id="ups_button" data-item_id='{$k2}' style="cursor:pointer;"/>
               <button type="button" id="btn{$k2}" data-spec_id='{$vo[id]}' data-item_id='{$k2}' class="btn <?php 
			   if(!empty($mytype)){
				  if(in_array($k2,$items_ids))                         
                     echo 'btn-success';
                  else 
                     echo 'btn-default'; 
			   }else{
				   echo 'btn-success';
			   } 
                 ?>" >
                    {$vo2}
                </button>
				<img id="mydel" rel="{$k2}" rev="{$vo[id]}" src="/Public/images/cancel.png" title="删除此规格属性"/>

                        <img width="35" height="35" src="https://xjt.zczmer.com/{$specImageList[$k2]|default='/Public/images/update_img.png'}" id="item_img_{$k2}" onclick="GetUploadify3('{$k2}');" style="cursor: pointer;"/>
                        <input type="hidden" name="item_img[{$k2}]" value="{$specImageList[$k2]}" />
						
						<div id="updates{$k2}" style="position:absolute;display:none;">
							<input type="text" maxlength="80" name="spec_items" contenteditable="true" class="form-control" onchange="updateSort2('spec_item','id','{$k2}','item',this);$('#btn{$k2}').text(this.value);$(this).parent().hide();" style="vertical-align: middle;display: initial" value="{$vo2}">
						</div>
						
                &nbsp;&nbsp;&nbsp;
				</span>
            </foreach>
<!-- <input type="text" onchange="updateSort('goods','goods_id','211','distribut',this)" onkeyup="this.value=this.value.replace(/[^\d]/g,'')" onpaste="this.value=this.value.replace(/[^\d]/g,'')" size="4" value="3" class="input-sm"> -->
            <input type="text" maxlength="80" data-spec_id="{$vo[id]}" name="spec_item" onkeydown="dianji(event)" placeholder="规格值名称" class="form-control" style="width:80px;vertical-align: middle;display: initial;">
            &nbsp;&nbsp;
            <a href="javascript:void(0);" onclick="addSpecItem(this)">添加<i style="color:#b0aeae;font-size: 12px;font-style:normal">（支持回车、左右拖拽排序）</i></a>
<!--            <a href="javascript:void(0);"  onclick="delSpecItem(this)">删除</a>  -->          
        </td>
    </tr>                                    
    </foreach>    
</table>
<div id="goods_spec_table2"> <!--ajax 返回 规格对应的库存--> </div>

<script>
    //鼠标位于 a标签上方时发生 mouseover 事件 
		$("#tab_goods_spec #ups_button").click(function(e){
		var mye=$(e.target);
        var mydata = mye.attr("data-item_id");
		var xx=mye.offset().top;
		var yy=mye.offset().left;
		var yuan=$("#btn"+mydata).width();
		var obj=$("#updates"+mydata);
		var pd=obj.css('display');
		//yuan=yuan.replace(/(^\s*)|(\s*$)/g, "");
		obj.find('input').css('width',(yuan+28)+'px');
		
		if(pd=='none'){
				obj.css('display','block');
				obj.css({"top": (xx)+1 + "px","left": (yy)+38 + "px"});
			}else{
				obj.css('display','none');
			}


    })
	
	//删除属性
	$("#tab_goods_spec #mydel").click(function(e){
		var obj=$(this); 
		var spec_item_id = obj.attr('rel');
		var spec_id = obj.attr('rev');
			layer.confirm('确定要删除此规格内容？', {
			  btn: ['确定','取消'] //按钮
			}, function(){
		$.ajax({
				type:'POST',
				data:{'spec_item_id':spec_item_id,'spec_id':spec_id},
				dataType:'json',
				url:"/index.php/Seller/Goods/delSpecItem",
				success:function(data){
					    if(data.status < 0)
					    {
						    layer.alert(data.msg, {icon: 2}); 
					    }else{
						   $("#goods_type").trigger('change');
						   obj.parent().remove();layer.closeAll();
					    }
					//layer.closeAll();
				}
		});
		});
	});

function dianji(e) {
        var evt = window.event || e;
        if (evt.keyCode == 13) {
		var spec_item = e.target.value;
		spec_item = $.trim(spec_item);
		var goods_id='{$mytype}';
		var spec_id = e.target.dataset.spec_id;
		if(spec_item.length == 0)
		{
			layer.alert('请输入规格值', {icon: 2});  //alert('删除失败');
			return false;
		}
		
		$.ajax({
				type:'POST',
				data:{'spec_item':spec_item,'spec_id':spec_id,'goods_id':goods_id},
				dataType:'json',
				url:"/index.php?m=Seller&c=Goods&a=addSpecItem",
				success:function(data){                            
					   if(data.status < 0)
					   {
						   layer.alert(data.msg, {icon: 2}); 
					   }else{
						  $("#goods_type").trigger('change');
					   }						   
				}
		});
        }
}
	
    // 添加规格
	function addSpecItem(obj){
		var spec_item = $(obj).siblings('input[name="spec_item"]').val();
		spec_item = $.trim(spec_item);
		var goods_id='{$mytype}';
		var spec_id = $(obj).siblings('input[name="spec_item"]').data('spec_id');
		if(spec_item.length == 0)
		{
			layer.alert('请输入规格值', {icon: 2});  //alert('删除失败');
			return false;
		}
		
		$.ajax({
				type:'POST',
				data:{'spec_item':spec_item,'spec_id':spec_id,'goods_id':goods_id},
				dataType:'json',
				url:"/index.php?m=Seller&c=Goods&a=addSpecItem",
				success:function(data){                            
					   if(data.status < 0)
					   {
						   layer.alert(data.msg, {icon: 2}); 
					   }else{
						  $("#goods_type").trigger('change');
					   }						   
				}
		});

	}
	
    // 删除规格
	function delSpecItem(obj){
		var spec_item = $(obj).siblings('input[name="spec_item"]').val();
		spec_item = $.trim(spec_item);
		var spec_id = $(obj).siblings('input[name="spec_item"]').data('spec_id');
		console.log(spec_item+"_"+spec_id);return;
		// if(spec_item.length == 0)
		// {
		// 	layer.alert('请输入规格值', {icon: 2});  //alert('删除失败');
		// 	return false;
		// }
		
		$.ajax({
				type:'POST',
				data:{'spec_item':spec_item,'spec_id':spec_id},
				dataType:'json',
				url:"/index.php/Seller/Goods/delSpecItem",
				success:function(data){                            
					   if(data.status < 0)
					   {
						   layer.alert(data.msg, {icon: 2}); 
					   }else{
						   $("#goods_type").trigger('change');
					   }						   
				}
		});

	}	

    
    // 上传规格图片
    function GetUploadify3(k){        
        cur_item_id = k; //当前规格图片id 声明成全局 供后面回调函数调用
        GetUploadify(1,'','goods','call_back3');
    }
    
    
    // 上传规格图片成功回调函数
    function call_back3(fileurl_tmp){
        $("#item_img_"+cur_item_id).attr('src',fileurl_tmp); //  修改图片的路径
        $("input[name='item_img["+cur_item_id+"]']").val(fileurl_tmp); // 输入框保存一下 方便提交
    }    
    
   // 按钮切换 class
   $("#ajax_spec_data button").click(function(){
	   if($(this).hasClass('btn-success'))
	   {
		   $(this).removeClass('btn-success');
		   $(this).addClass('btn-default');		   
	   }
	   else
	   {
		   $(this).removeClass('btn-default');
		   $(this).addClass('btn-success');		   
	   }
	   ajaxGetSpecInput();	  	   	 
});
	

/**
*  点击商品规格触发 下面输入框显示
*/
function ajaxGetSpecInput()
{
//	  var spec_arr = {1:[1,2]};// 用户选择的规格数组 	  
//	  spec_arr[2] = [3,4]; 
	  var spec_arr = {};// 用户选择的规格数组 	  	  
	// 选中了哪些属性	  
	$("#goods_spec_table1  button").each(function(){
	    if($(this).hasClass('btn-success'))	
		{
			var spec_id = $(this).data('spec_id');
			var item_id = $(this).data('item_id');
			if(!spec_arr.hasOwnProperty(spec_id))
				spec_arr[spec_id] = [];
		    spec_arr[spec_id].push(item_id);
			
		}		
	});
		ajaxGetSpecInput2(spec_arr); // 显示下面的输入框
	
}
	
	
/**
* 根据用户选择的不同规格选项
* 返回 不同的输入框选项
*/
function ajaxGetSpecInput2(spec_arr)
{		
    var goods_id = $("input[name='goods_id']").val();
	$.ajax({
			type:'POST',
			data:{'spec_arr':spec_arr},
			url:"/index.php/Seller/Goods/ajaxGetSpecInput/goods_id/"+goods_id,
			success:function(data){
				   $("#goods_spec_table2").html('');
				   $("#goods_spec_table2").append(data);
				   hbdyg();  // 合并单元格
			}
	});
}
	
 // 合并单元格
 function hbdyg() {
            var tab = document.getElementById("spec_input_tab"); //要合并的tableID
            var maxCol = 2, val, count, start;  //maxCol：合并单元格作用到多少列  
            if (tab != null) {
                for (var col = maxCol - 1; col >= 0; col--) {
                    count = 1;
                    val = "";
                    for (var i = 0; i < tab.rows.length; i++) {
                        if (val == tab.rows[i].cells[col].innerHTML) {
                            count++;
                        } else {
                            if (count > 1) { //合并
                                start = i - count;
                                tab.rows[start].cells[col].rowSpan = count;
                                for (var j = start + 1; j < i; j++) {
                                    tab.rows[j].cells[col].style.display = "none";
                                }
                                count = 1;
                            }
                            val = tab.rows[i].cells[col].innerHTML;
                        }
                    }
                    if (count > 1) { //合并，最后几行相同的情况下
                        start = i - count;
                        tab.rows[start].cells[col].rowSpan = count;
                        for (var j = start + 1; j < i; j++) {
                            tab.rows[j].cells[col].style.display = "none";
                        }
                    }
                }
            }
        }
</script> 